package org.lyq.erp.auth.role.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.lyq.erp.auth.role.mapper.RoleMapper;
import org.lyq.erp.auth.role.pojo.Role;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleServiceImpl implements RoleService {
	
	@Resource
	private RoleMapper roleMapper;

	public List<Role> selectAllRole() {
		return this.roleMapper.selectAllRole();
	}

	@Transactional
	public void insert(Role role) {
		role.setCreatetime(Long.valueOf(System.currentTimeMillis()));
		role.setUpdatetime(Long.valueOf(System.currentTimeMillis()));
		this.roleMapper.insertSelective(role);

		Integer[] resUuids = role.getResUuids();
		Integer[] menuUuids = role.getMenuUuids();
		insertResAndMenu(resUuids, menuUuids, role.getRoleUuid());
	}

	@Transactional
	public void update(Role role) {
		Integer[] resUuids = role.getResUuids();
		Integer[] menuUuids = role.getMenuUuids();
		Integer roleUuid = role.getRoleUuid();

		role.setUpdatetime(Long.valueOf(System.currentTimeMillis()));

		this.roleMapper.updateByPrimaryKeySelective(role);

		this.roleMapper.deleteAllResource(roleUuid);

		this.roleMapper.deleteAllMenu(roleUuid);

		insertResAndMenu(resUuids, menuUuids, roleUuid);
	}

	public Role getRoleByRoleUuid(Integer roleUuid) {
		return this.roleMapper.selectRoleByRoleUuid(roleUuid);
	}

	@Transactional
	public void delete(Integer roleUuid) {
		this.roleMapper.deleteRoleByRoleUuid(roleUuid);

		this.roleMapper.deleteAllResource(roleUuid);

		this.roleMapper.deleteAllMenu(roleUuid);

		this.roleMapper.deleteAllEmployee(roleUuid);
	}

	private void insertResAndMenu(Integer[] resUuids, Integer[] menuUuids, Integer roleUuid) {
		List<Integer> list = new ArrayList<Integer>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleUuid", roleUuid);

		if (resUuids != null) {

			for (int i = 0; i < resUuids.length; i++) {
				list.add(resUuids[i]);
			}
			map.put("list", list);

			this.roleMapper.insertRoleAndResource(map);
		}
		if (menuUuids != null) {

			list.clear();

			for (int j = 0; j < menuUuids.length; j++) {
				list.add(menuUuids[j]);
			}
			map.put("list", list);

			this.roleMapper.insertRoleAndMenu(map);
		}

		list = null;
		map = null;
	}
}
